# coding:utf-8

import collections


FieldName = collections.namedtuple('FieldName', 'index name')


class DBSET(object):

    def __init__(self, statements, connection, dbapi):
        self.statement = statements
        self.connection_data = connection
        self.dbapi = __import__(dbapi, globals())

    def execute(self, sql, params, auto_commit=False):
        conn = self.dbapi.connect(**self.connection_data)
        cursor = conn.cursor()
        ret = cursor.execute(sql, params)
        if auto_commit:
            conn.commit()
        return ret

    def search(self, params):
        sql = self.statement['select']
        cursor = self.execute(sql, params)
        ret = []
        field = [FieldName(index, name[0]) for index, name
                    in enumerate(cursor.description)]
        for row in cursor:
            ret.append(dict((f.name, row[f.index]) for f in field))
        return tuple(ret)

    def update(self, params):
        sql = self.statement['update']
        self.execute(sql, params, True)

    def new(self, params):
        sql = self.statement['insert']
        self.execute(sql, params, True)

    def delete(self, params):
        sql = self.statement['delete']
        self.execute(sql, params, True)
